import openpyxl
import os
import requests
import pandas as pd

INPUT_FILE = 'download_file.xlsx'
IMAGES_FOLDER = 'images'


# 如果发现无法下载，直接运行此函数更快捷
def test():
    url = 'http://store-vivofs-beijing-2.oss-cn-beijing.aliyuncs.com/aAAdUPJLUOyPd4VK/ai-vcode/2021-10-20/9ceff357-f508-48d6-bd52-659ac324aa8aF_1_9_07795e5b5bff9ba558f71634682936317.pcm'
    resp = requests.get(url)
    if resp.status_code == 200:
        full = os.path.join(IMAGES_FOLDER, 'test' + '.pcm')
        with open(full, 'wb') as f:
            f.write(resp.content)
            print(full)
    else:
        print(resp.status_code)
        print(resp.reason)
        print(resp.text)
    exit(0)


def testnum():
    s = '865386054850554'
    n = int(s)
    print(n > 3)
    exit(0)


if __name__ == '__main__':

    if not os.path.isdir(IMAGES_FOLDER):
        os.mkdir(IMAGES_FOLDER)
    # testnum()
    # test()
    df = pd.read_excel(INPUT_FILE)
    # print(df)
    for i, row in df.iterrows():
        url = str(row['file_link'])
        fn = row['file_name']
        # 截取数字最后一位
        num_last1 = str(row['num'])[-1]
        # 如果不是1 2 3则跳过
        if not num_last1 in ['1', '2', '3']:
            continue
        print(url)
        # print(fn)
        resp = requests.get(url)
        if resp.status_code == 200:  # 网络成功返回
            ext = url[-4:]  # 截取url最后4位为扩展名
            full = os.path.join(IMAGES_FOLDER, fn + ext)
            with open(full, 'wb') as f:
                f.write(resp.content)
                print(full)
        else:
            # 输出网络错误
            print(resp.status_code)
            print(resp.reason)
            print(resp.text)
